package com.sunxd.study.easyrules.core;

import com.sunxd.study.easyrules.api.Facts;
import com.sunxd.study.easyrules.api.Rule;
import com.sunxd.study.easyrules.api.Rules;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @author sun.xd
 * @description: description
 * @date 2022/3/29 19:43
 */
public class DefaultRulesEngine extends AbstractRulesEngine {

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRulesEngine.class);


    @Override
    public void fire(Rules rules, Facts facts) {
        Objects.requireNonNull(rules, "Rules must not be null");
        Objects.requireNonNull(facts, "Facts must not be null");
        doFire(rules, facts);
    }

    public void doFire(Rules rules, Facts facts){
        if (rules.isEmpty()) {
            LOGGER.warn("No rules registered! Nothing to apply");
            return;
        }
        for (Rule rule: rules){
            String ruleName = rule.getName();
            int priority = rule.getPriority();
            if(rule.evaluate(facts)){
                try {
                    rule.execute(facts);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
